class Solution {
public:
    unordered_map<int, vector<int>> ma;
    bool flag[100005] = { 0 };
    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
        for (auto& x : edges)
        {
            ma[x[0]].push_back(x[1]);
            ma[x[1]].push_back(x[0]);
        }
        dfs1(0, -1, hasApple);
        int ans = 0;
        dfs2(0, -1, ans);
        return ans;
    }
    bool dfs1(int pos, int pre, vector<bool>& hasApple)
    {
        if (hasApple[pos]) flag[pos] = 1;
        for (auto& x : ma[pos])
        {
            if (x == pre) continue;
            flag[pos] |= dfs1(x, pos, hasApple);
        }
        return flag[pos];
    }
    void dfs2(int pos, int pre, int& ans)
    {
        for (auto& x : ma[pos])
        {
            if (x == pre) continue;
            if (!flag[x]) continue;
            ans += 1;
            dfs2(x, pos, ans);
            ans += 1;
        }
    }
};